﻿using Furion.DynamicApiController;
using Furion.UnifyResult;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using XREditor.Models;

namespace XREditor.Controllers
{
    /// <summary>
    /// 系统初始化
    /// </summary>
    [DynamicApiController]
    [ApiDescriptionSettings(Order = 5000)]
    public class InitController
    {
        private readonly ILogger<InitController> logger;
        private readonly ISqlSugarClient db; // 核心对象：拥有完整的SqlSugar全部功能
        public InitController(ISqlSugarClient sqlSugarClient)
        {
            this.db = sqlSugarClient;
            this.logger = logger;
        }

        /// <summary>
        /// 初始化数据库、表结构、默认数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> CreateDbAndTables()
        {
            #region 创建数据库并修改编码
            //db.DbMaintenance.CreateDatabase("kkxsys");
            //await db.Ado.ExecuteCommandAsync("ALTER DATABASE `kkxsys` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
            #endregion

            #region 创建表
            //db.CodeFirst.InitTables<MoXing>();
            //db.CodeFirst.InitTables<Category>();
            //db.CodeFirst.InitTables<Project>();
            db.CodeFirst.InitTables<ProjectHistory>();
            #endregion

            #region 生成不可删除的默认基数据和字典表
            db.Insertable<ProjectHistory>(new ProjectHistory { Id = 0, LastOpId = 0 }).ExecuteCommandAsync();
            #endregion

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = "初始化数据库、表结构、默认数据成功！！！",
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 测试接口
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Test()
        {
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = null,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }
    }
}
